package com.xw.controller.other;

import com.xw.utils.EnclosureUtil;
import com.xw.utils.FileUtil;
import com.xw.utils.PathUtil;
import com.xw.vo.ResultVO;
import org.springframework.http.MediaType;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Description:
 * @Author: y
 * @CreateDate: 2020-07-31 16:37
 * @Version: 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @RequestMapping(value = "/viewUploadFile", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] viewUpload(@RequestParam("id") String id) throws IOException {

        if (!ObjectUtils.isEmpty(id)) {
            File file = new File(PathUtil.getImgBasePath() + id);
            if (!file.exists()) {
                return null;
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }
        return null;

    }

    /**
     * editor文件上传
     */
    @RequestMapping("/editor/fileUpload")
    public String fileUpload(@RequestParam("upload") MultipartFile multipartFile) {
        return EnclosureUtil.saveEnclosure(multipartFile);
    }


    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public ResultVO<?> fileUpload(MultipartFile photo, HttpServletRequest request) {
        return FileUtil.saveFile(photo, request);
    }

}
